/**
 * Created by zhnh9 on 8/13/2016.
 */

var EventUtil = {
    addHandler: function(element, type, handler) {
        if (element.addEventListener) {
            element.addEventListener(type, handler, false);
        } else if (element.attachEvent) {
            element.attachEvent("on" + type, handler);
        } else {
            element["on" + type] = handler;
        }
    },
    removeHandler: function(element, type, handler) {
        if (element.removeEventListener) {
            element.removeEventListener(type, handler, false);
        } else if (element.detachEvent) {
            element.detachEvent("on" + type, handler);
        } else {
            element["on" + type] = null;
        }
    }
};

/**
 * @author Dawn on 2016-02-25.
 */
var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1));
    var sURLVariables = sPageURL.split('&');
    var sParameterName = undefined;

    for (var i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

var apiUrl = "http://172.16.100.205:8080";
//var apiUrl = "http://192.168.1.48:8080";

var AjaxIO = {

    _getUrl: function(action) {
        return apiUrl + action + ".do";
    },

    _ajax: function(url, method, param, callback, fail_callback) {

        if (callback == undefined) {
            callback = param;
        }
        var token = localStorage.getItem('token');
        var headers = undefined;
        if (token != null) {
            // headers = {'Authorization': 'Basic ' + token};
            param.Authorization = 'Basic ' + token;
        }
        $.ajax({
            url: this._getUrl(url),
            data: param,
            dataType: 'json',
            // headers:headers,
            method: method,
            statusCode: {
                401: function(result) {},
                404: function() {

                },
                201: function() {

                },
                202: function() {

                }
            },
            success: callback,
            error: fail_callback
        });
    },

    getJSON: function(url, param, callback, fail_callback) {

        this._ajax(url, "GET", param, callback, fail_callback);

    },

    post: function(url, param, callback, fail_callback) {

        this._ajax(url, "POST", param, callback, fail_callback)
    }
};


var StringUtils = {
    isEmpty: function(str) {
        if (!str) {
            //str is empty
            return true;
        }
        return false;

    },

    isNotEmpty: function(str) {
        return !this.isEmpty(str);
    }
};


/**
 * 分页
 */
function PageKit(params, pageEvent) {
    this.divId = params.id;
    this.totalPage = params.totalPage;
    this.currentPage = 1;
    this.pageSkipEvent = pageEvent;
    var _self = this;
    var pageDiv = $('#' + _self.divId);
    pageDiv.html("");
    pageDiv.append("<a class='page-up' href='javascript:void(0)' >上一页</a>");
    pageDiv.append("<span class='first-num'>1/" + params.totalPage + "</span>");
    pageDiv.append("<a class='page-down' href='javascript:void(0)'>下一页</a>");
    pageDiv.append("<input type='text' class='inputPage'>");
    pageDiv.append("<button class='btn btn-primary'>跳转</button>");

    pageDiv.on('click', 'button', function() {
        var inputValue = _self._inputValue();
        if (isNaN(inputValue)) {
            return;
        }

        _self.skipToPage(parseInt(inputValue));
    });

    //上一页
    pageDiv.on('click', '.page-up', function() {
        _self.skipToPage(_self.currentPage - 1);
    });

    //下一页
    pageDiv.on('click', '.page-down', function() {
        _self.skipToPage(_self.currentPage + 1);
    });
}

function news() {
    var none = {

    }

    AjaxIO.post("/news/newsList", none,
        function(result) {
            var ul = document.getElementById("news_ul");
            for (var i = 0; i < result.data.newsList.length; i++) {
                var li = document.createElement("li");
                var a = document.createElement("a");
                var div_img = document.createElement("div");
                var img = document.createElement("img");
                var div1 = document.createElement("div");
                var div2 = document.createElement("div");
                var div3 = document.createElement("div");
                var n_id = document.createElement("span");

                a.setAttribute("href", "#");
                img.setAttribute("src", result.data.newsList[i].n_img);
                img.setAttribute("style", "width: 4rem;");
                n_id.setAttribute("style", "display: none;");

                //添加css
                a.className = "item-link item-content";
                div_img.className = "item-media";
                div1.className = "item-inner";
                div2.className = "item-title-row";
                div3.className = "item-text";
                div3.innerHTML = result.data.newsList[i].n_title;
                n_id.innerHTML = result.data.newsList[i].n_id;

                //进行拼装
                div2.appendChild(n_id);
                div2.appendChild(div3);
                div1.appendChild(div2);
                div_img.appendChild(img);
                a.appendChild(div_img);
                a.appendChild(div1);
                li.appendChild(a);
                ul.appendChild(li);
            }
            $(".item-link").click(function() {
                var n_id = $(this).find("span")[0].innerText;
                localStorage.setItem("n_id", n_id);
                window.location.href = "news.html";
            })
        })
}
    
    PageKit.prototype._inputValue = function() {
        return $('#' + this.divId + ' input').val()
    };

    PageKit.prototype.skipToPage = function(pageNum) {
        if (isNaN(pageNum) || pageNum < 1 || pageNum > this.totalPage) {
            return;
        }

        $('#' + this.divId + ' .first-num').html(pageNum + "/" + this.totalPage);
        this.currentPage = pageNum;
        $('#' + this.divId + ' input').val('');
        this.pageSkipEvent(pageNum);
    };

    var Page = {

        render: function(params, pageEvent) {
            return new PageKit(params, pageEvent);
        }
    };

    function getEl(ElementId) {
        return document.getElementById(ElementId);
    }


    function seriesSelect() {
        var infoseriesselect = {
            c_brand: localStorage["brand"],
        }

        AjaxIO.post("/computer/seriesSelect", infoseriesselect,
            function(result) {
                var ul = getEl("ul");
                for (var i = 0; i < result.data.computerList.length; i++) {
                    var li = document.createElement("li");
                    var a = document.createElement("a");
                    a.setAttribute("href", i);
                    a.className = "item-link item-content";
                    var div1 = document.createElement("div");
                    div1.className = "item-media";
                    var img = document.createElement("img");
                    img.setAttribute("src", "/" + result.data.computerList[i].c_filesrc);
                    img.setAttribute("style", "width: 2.2rem;");
                    var div2 = document.createElement("div");
                    div2.className = "item-inner";
                    var div3 = document.createElement("div");
                    div3.className = "item-title-row";
                    var div4 = document.createElement("div");
                    div4.className = "item-title";
                    div4.innerHTML = result.data.computerList[i].c_series;

                    div3.appendChild(div4);
                    div2.appendChild(div3);
                    div1.appendChild(img);
                    a.appendChild(div1);
                    a.appendChild(div2);
                    li.appendChild(a);
                    ul.appendChild(li);
                }
                $(".item-link").click(function() {
                    var c_series = $(this).find("div.item-title")[0].innerText;
                    localStorage.setItem("c_series", c_series);
                    window.location.href = "selectType.html";
                })
            },
            function(result) {
                $.toast("no match");
            }
        );
    }

    function typeSelect() {
        var infotypeselect = {
            c_series: localStorage["c_series"],
        }
        AjaxIO.post("/computer/typeSelect", infotypeselect,
            function(result) {
                var ul = getEl("ul");

                for (var i = 0; i < result.data.computerList.length; i++) {
                    var li = document.createElement("li");
                    var a = document.createElement("a");
                    a.setAttribute("href", "#");
                    a.className = "item-link item-content";
                    var div2 = document.createElement("div");
                    div2.className = "item-inner";
                    var div3 = document.createElement("div");
                    div3.className = "item-title-row";
                    var div4 = document.createElement("div");
                    div4.className = "item-title";
                    div4.innerHTML = result.data.computerList[i].c_type;
                    var div1 = document.createElement("div");
                    div1.className = "id";
                    div1.setAttribute("style", "display: none;");
                    div1.innerHTML = result.data.computerList[i].c_id;

                    div3.appendChild(div4);
                    div2.appendChild(div3);
                    a.appendChild(div1);
                    a.appendChild(div2);
                    li.appendChild(a);
                    ul.appendChild(li);
                }
                $(".item-link").click(function() {
                    var c_id = $(this).find("div.id")[0].innerText;
                    localStorage.setItem("c_id", c_id);
                    window.location.href = "computermsg.html";

                });

            },
            function(result) {
                $.toast("no match");
            });

    }

    function massageSelect() {


        var infomassageselect = {
            c_id: localStorage["c_id"],
            m_id: localStorage["m_id"],
        }
        AjaxIO.post("/computer/massageSelect", infomassageselect,
            function(result) {
                var img = getEl("img");
                img.setAttribute("src", "/" + result.data.computerList.c_filesrc);
                var c_type = getEl("c_type");
                c_type.innerHTML = result.data.computerList.c_type;
            }
        )
        AjaxIO.post("/computer/relationSelect", infomassageselect,
            function(result) {

                $("#mycomputer").css("display", "none");
                $("#deletemycomputer").css("display", "block");
            },
            function(result) {
                if (result.status == 401) {
                    $("#mycomputer").css("display", "block");
                    $("#deletemycomputer").css("display", "none");
                }
            }
        )

        $("#mycomputer").click(function() {
            AjaxIO.post("/computer/mycomputer", infomassageselect,
                function(result) {

                    $.toast("添加成功");
                    window.location.reload();

                },
                function(result) {
                    if (result.status == 201) {
                        $.toast("已存在");
                    }
                })
        });


        $("#deletemycomputer").click(function() {
            AjaxIO.post("/computer/deletemycomputer", infomassageselect,
                function(result) {

                    $.toast("删除成功");
                    window.location.reload();
                },
                function(result) {
                    if (result.status == 404) {
                        $.tosat("删除失败");

                    }
                }
            )
        });
    }

    function selectComputer() {
        var info = {
            m_id: localStorage["m_id"]
        }
        AjaxIO.post("/computer/mycomputerSelect", info,
            function(result) {
                var ul = getEl("ul");
                for (var i = 0; i < result.data.computerList.length; i++) {
                    var li = document.createElement("li");
                    var a = document.createElement("a");
                    a.setAttribute("href", "#");
                    a.className = "item-link item-content";
                    var div2 = document.createElement("div");
                    div2.className = "item-inner";
                    var div3 = document.createElement("div");
                    div3.className = "item-title-row";
                    var div4 = document.createElement("div");
                    div4.className = "item-title";
                    div4.innerHTML = result.data.computerList[i].c_type;
                    var div1 = document.createElement("div");
                    div1.className = "id";
                    div1.setAttribute("style", "display: none;");
                    div1.innerHTML = result.data.computerList[i].c_id;

                    div3.appendChild(div4);
                    div2.appendChild(div3);
                    a.appendChild(div1);
                    a.appendChild(div2);
                    li.appendChild(a);
                    ul.appendChild(li);
                }

                $(".item-link").click(function() {
                    var c_id = $(this).find("div.id")[0].innerText;
                    localStorage.setItem("c_id", c_id);
                    window.location.href = "selectenginer.html";


                })
            })
    }

    function master() {
        var infoblock = {}
        AjaxIO.post("/master/block", infoblock,
            function(result) {
                function addItems(number, lastIndex) {
                    // 生成新条目的HTML
                    var html = '';
                    for (var i = lastIndex + 0; i <= lastIndex + number; i++) {
                        html += '<li><div><div style="display:inline-block;width:10%;color:#246183;"><input type="radio" name="onlyone" class="remember"><span class="checkbox"></span></div><div style="display:inline-block;width:23%;height:auto;background:#fff;"><img src=' + result.data.computerList[i].e_filesrc + ' class="image" style="width:65px;height:65px;"></div><div style="width:63%;display:inline-block;margin-left:10px;padding:0"><ul class="content_center" style="padding:3px;"><li><label class="name">' + result.data.computerList[i].e_name + '</label><label style="display:none" class="e_id">' + result.data.computerList[i].e_id + '</label></li><li><p>评价：<span>' + result.data.computerList[i].e_garde + '</span></p><p>预约次数：<span>' + result.data.computerList[i].e_reservation + '</span></p></li><li><img src="/img/job.png" class="smallpic"><p>' + result.data.computerList[i].e_job + '</p></li><li class="line"><img src="/img/worktime.png" class="smallpic"><span>' + result.data.computerList[i].e_worktime + '</span></li><li>' + result.data.computerList[i].e_major + '</li></ul></div></div></li>';
                    }
                    $('.infinite-scroll-bottom .list-container').append(html);
                    var m_id = 0;
                    $("input.remember").change(function() {
                        m_id = $(this).parent().parent().find("label.e_id")[0].innerText;
                        $("#e_id").html(m_id);
                    });
                }

                // 加载flag
                var loading = false;
                // 最多可加载的条目
                var maxItems = result.length;
                // 每次加载添加多少条目
                var itemsPerLoad = 20;
                //预先加载20条
                addItems(itemsPerLoad - 1, 0);
                // 上次加载的序号
                var lastIndex = 20;
                // 注册'infinite'事件处理函数
                $(document).on('infinite', '.infinite-scroll-bottom', function() {
                    // 如果正在加载，则退出
                    if (loading) return;
                    // 设置flag
                    loading = true;
                    // 模拟1s的加载过程
                    setTimeout(function() {
                        // 重置加载flag
                        loading = false;
                        if (lastIndex >= maxItems) {
                            // 加载完毕，则注销无限加载事件，以防不必要的加载
                            $.detachInfiniteS
                            croll($('.infinite-scroll'));
                            // 删除加载提示符
                            $('.infinite-scroll-preloader').remove();
                            return;
                        }
                        // 添加新条目
                        addItems(itemsPerLoad, lastIndex);
                        // 更新最后加载的序号
                        lastIndex += 21;
                        //容器发生改变,如果是js滚动，需要刷新滚动
                        $.refreshScroller();
                    }, 1000);
                });


            });

        $("button.pull-right").click(function() {
            var e_id = $("#e_id").html();
            if (e_id == "none")
                $.toast("请选择师傅");
            else {

                localStorage.setItem("e_id", e_id);
                window.location.href = "orderisOk.html"

            }
        });
    }

    function ordermsg() {
        var info = {
            o_id: localStorage["o_id"],
        }
        AjaxIO.post("/order/orderSelectByo_id", info,
            function(result) {
                getEl("o_id").innerHTML = result.data.computerList.o_id;
                getEl("c_type").innerHTML = result.data.computerList.c_type;
                getEl("o_project").innerHTML = result.data.computerList.o_project;
                getEl("o_condition").innerHTML = result.data.computerList.o_condition;
                getEl("o_confirmtime").innerHTML = result.data.computerList.o_confirmtime;
                getEl("e_tele").innerHTML = result.data.computerList.e_tele;
                getEl("e_name").innerHTML = result.data.computerList.e_name;
            })

        $("#deleteOrder").click(function() {
            AjaxIO.post("/order/deleteOrder", info,
                function(result) {
                    alert("订单取消成功");
                    window.location.href = "index.html";
                },
                function(result) {
                    alert("订单取消失败");
                }
            )
        })

    }

    function orderisok() {
        var info = {
            c_id: localStorage["c_id"],
            e_id: localStorage["e_id"],
            m_id: localStorage["m_id"],
            o_project: localStorage["orderFix"],
            o_realname: localStorage["orderName"],
            o_sex: localStorage["orderSex"],
            o_tele: localStorage["orderTel"],
            o_address: localStorage["orderAddress"],
        }
        AjaxIO.post("/order/orderInster", info,
            function(result) {

                $.toast("订单已建立")

            },
            function(result) {
                $.toast("建立订单失败")

            }
        )

    }

    function myorder() {
        var info = {
            m_id: localStorage["m_id"],
        }


        AjaxIO.post("/order/orderSelectBym_id", info,
            function(result) {
                for (var i = 0; i < result.data.computerList.length; i++) {
                    var orderlist = document.getElementById("orderlist");
                    var block = document.createElement("div");
                    var button = document.createElement("div"); //下边
                    var fix = document.createElement("label"); //维修项目
                    var oDiv = document.createElement("div"); //包含p,a
                    var fixcontent = document.createElement("p"); //维修项目内容
                    var goto = document.createElement("a"); //跳转到详情
                    var img = document.createElement("img"); //详情
                    var top = document.createElement("div"); //上边
                    var time = document.createElement("p"); //登记时间
                    var condition = document.createElement("p"); //状态
                    var o_id = document.createElement("div");


                    img.setAttribute("src", "/img/forwardbutton.png");
                    goto.setAttribute("href", "#");
                    fix.innerHTML = result.data.computerList[i].c_type;
                    fixcontent.innerHTML = result.data.computerList[i].o_project;
                    time.innerHTML = result.data.computerList[i].o_confirmtime;
                    condition.innerHTML = result.data.computerList[i].o_condition;
                    o_id.innerHTML = result.data.computerList[i].o_id;

                    //添加css
                    block.className = "_block";
                    top.className = "_top";
                    time.className = "_time";
                    condition.className = "_condition";
                    button.className = "_button";
                    fix.className = "_fix";
                    oDiv.className = "_oDiv";
                    fixcontent.className = "_fixcontent";
                    goto.className = "_goto";
                    img.className = "_image";
                    o_id.className = "_o_id";
                    $(o_id).css("display", "none");

                    //进行拼装
                    orderlist.appendChild(block);
                    block.appendChild(top);
                    top.appendChild(time);
                    top.appendChild(condition);
                    block.appendChild(button);
                    button.appendChild(fix);
                    button.appendChild(oDiv);
                    oDiv.appendChild(fixcontent);
                    oDiv.appendChild(goto);
                    goto.appendChild(img);
                    block.appendChild(o_id);
                }

                $("div._block").click(function() {
                    var o_id = $(this).find("div._o_id")[0].innerHTML;
                    localStorage.setItem("o_id", o_id);
                    window.location.href = "ordermsg.html";
                });
            }
        )

    }

    function mycomputer() {
        var info = {
            m_id: localStorage["m_id"],
        }
        AjaxIO.post("/computer/mycomputerSelect", info,
            function(result) {
                var ul = getEl("ul");

                for (var i = 0; i < result.data.computerList.length; i++) {
                    var li = document.createElement("li");
                    var a = document.createElement("a");
                    a.setAttribute("href", "#");
                    a.className = "item-link item-content";
                    var div2 = document.createElement("div");
                    div2.className = "item-inner";
                    var div3 = document.createElement("div");
                    div3.className = "item-title-row";
                    var div4 = document.createElement("div");
                    div4.className = "item-title";
                    div4.innerHTML = result.data.computerList[i].c_type;
                    var div1 = document.createElement("div");
                    div1.className = "id";
                    div1.setAttribute("style", "display: none;");
                    div1.innerHTML = result.data.computerList[i].c_id;

                    div3.appendChild(div4);
                    div2.appendChild(div3);
                    a.appendChild(div1);
                    a.appendChild(div2);
                    li.appendChild(a);
                    ul.appendChild(li);
                }

                $(".item-link").click(function() {
                    var c_id = $(this).find("div.id")[0].innerText;
                    localStorage.setItem("c_id", c_id);
                    window.location.href = "computermsg.html";
                })
            })

    }

    function ifempty(el) {
        if (el.value != "") {
            $(el).parent().children("span").css("display", "none");
            return true;
        } else {
            $(el).parent().children("span").css("display", "inline-block");
            return false;
        }
    }



    function changecontent(tab_active, tab_none1, tab_none2, content_block, content_none1, content_none2) {
        return function() {
            tab_active.className = "tab-item active";
            tab_none1.className = "tab-item";;
            tab_none2.className = "tab-item";;
            content_block.style.display = "block";
            content_none1.style.display = "none";
            content_none2.style.display = "none";
        }
    }
    $(document).ready(function() {

        var enterButtonlogin = getEl("enterButtonlogin");
        EventUtil.addHandler(enterButtonlogin, "click", function() {
            var infologin = {
                m_name: document.getElementsByName("m_namelogin")[0].value,
                m_password: document.getElementsByName("m_passwordlogin")[0].value,
            };


            AjaxIO.post("/user/login", infologin,
                function(result) {

                    if (result.data.token) {
                        localStorage.setItem("m_id", result.data.m_id[0]);
                        localStorage.setItem("token", result.data.token);
                        location.href = "firstpage.html";
                    }
                },
                function(result) {
                    if (result.status == 404)
                        $.toast("请输入用户名");
                    if (result.status == 403)
                        $.toast("密码不正确");
                }
            );
        });

    });

    $(document).ready(function() {
        $("#enterButtonregister").click(function() {
            var imput_name = document.getElementsByName("m_name")[0];
            var imput_nicknanme = document.getElementsByName("m_nicknanme")[0];
            var imput_password = document.getElementsByName("m_password")[0];
            var m_name = imput_name.value;
            var m_sex = document.getElementsByName("m_sex")[0].value;
            var m_nicknanme = imput_nicknanme.value;
            var m_password = imput_password.value;
            var m_tele = document.getElementsByName("m_tele")[0].value;
            var m_address = document.getElementsByName("m_address")[0].value;
            var inforegister = {
                m_name: m_name,
                m_sex: m_sex,
                m_nicknanme: m_nicknanme,
                m_password: m_password,
                m_tele: m_tele,
                m_address: m_address,
            };
            AjaxIO.post("/user/register", inforegister,
                function(result) {
                    alert("注册成功");
                    location.href = "login.html";

                },
                function(result) {
                    if (result.status == 401)
                        $.toast("该用户已存在");


                }
            );

        });
    });
    $(document).ready(function() {
        var sideBarIndex = 0;
        $("#indeximg").click(function() {
            var body = $("#indexbody");
            var div = $("#sideBar");
            if (!sideBarIndex) {
                div.animate({
                    left: '0'
                }, "fast");
                body.animate({
                    left: '60%'
                }, "fast");
                sideBarIndex = !sideBarIndex;
            } else {
                div.animate({
                    left: '-60%'
                }, "fast");
                body.animate({
                    left: '0'
                }, "fast");
                sideBarIndex = !sideBarIndex;
            }
        });
        var infosliderbar = {
            m_id: localStorage["m_id"],
        }
        AjaxIO.post("/user/slidebar", infosliderbar,
            function(result) {
                var img = getEl("slidebarimg");
                img.setAttribute("src", "/" + result.data.customMsg[1]);
                var slidename = getEl("slidebarName");
                slidename.innerHTML = result.data.customMsg[0];
                var slideTel = getEl("slidebarTel");
                slideTel.innerHTML = result.data.customMsg[2];
            },
            function(result) {});

    });
    $(document).ready(function() {

        var width = $(".edging").css("width");
        var img_width = $(".edging img").css("width");
        var img_height = $(".edging img").css("height");
        var news_tab = getEl("news_tab");
        var order_tab = getEl("order_tab");
        var com_tab = getEl("com_tab");
        var news_content = getEl("news_content");
        var order_content = getEl("order_content");
        var com_content = getEl("com_content");



        $(".edging").css("height", width);
        $(".edging").css("border-radius", width);

        if (img_width > img_height) {
            $(".edging img").css("height", width);
        } else {
            $(".edging img").css("width", width);
        }
        $(".item-link").click(function() {
            var brand = $(this).find("div.item-title")[0].innerText;
            localStorage.setItem("brand", brand);
            window.location.href = "selectSeries.html";
        });
        $("#submitorder").click(function() {
            localStorage.setItem("orderName", document.getElementsByName("orderName")[0].value);
            localStorage.setItem("orderSex", document.getElementsByName("orderSex")[0].value);
            localStorage.setItem("orderAddress", document.getElementsByName("orderAddress")[0].value);
            localStorage.setItem("orderType", document.getElementsByName("orderType")[0].value);
            localStorage.setItem("orderFix", document.getElementsByName("orderFix")[0].value);
            localStorage.setItem("orderTel", document.getElementsByName("orderTel")[0].value);
            location.href = "selectComputer.html"

        });
        $("#quit").click(function() {
            localStorage.clear();
        });


        EventUtil.addHandler(news_tab, "click",
            changecontent(news_tab, order_tab, com_tab, news_content, order_content, com_content));

        EventUtil.addHandler(order_tab, "click",
            changecontent(order_tab, news_tab, com_tab, order_content, news_content, com_content));

        EventUtil.addHandler(com_tab, "click",
            changecontent(com_tab, order_tab, news_tab, com_content, order_content, news_content));



    });